from typing import List
from peewee import *

from common.enum.stock_category_enum import StockCategoryEnum
from dto.strategy_bind_setting_dto import StrategyBindingDTO
from service.das.database_pool import DatabasePool


class StrategyBinding(Model):
    id = AutoField()  # 自增主键
    stock_category = CharField(max_length=50)  # 股票分类
    stock_code = CharField(max_length=20, null=True)  # 股票代码（可为空）
    strategies = TextField()  # 策略列表（存储为逗号分隔的字符串）

    # 新增字段
    strategy_code = CharField(max_length=50)  # 策略代码
    strategy_name = CharField(max_length=100)  # 策略可读名称
    strategy_group = CharField(max_length=100)  # 策略分组
    strategy_type = CharField(max_length=100)  # 策略类型
    analysis_day = IntegerField(default=0)  # 策略分析的天数
    strategy_level = IntegerField(default=1)  # 策略等级

    class Meta:
        database = DatabasePool(max_connections=5).database
        table_name = "strategy_bind_setting"


class StrategyBindingService:
    @staticmethod
    def add_or_update_strategy(dto: StrategyBindingDTO) -> StrategyBindingDTO:
        """添加或更新绑定策略"""
        # 查找是否存在相同分类和股票代码的记录
        query = StrategyBinding.select().where(
            (StrategyBinding.stock_category == dto.stock_category.value[0])
            & (StrategyBinding.stock_code == dto.stock_code)
        )
        try:
            binding = query.get()
            # 更新策略列表
            binding.strategies = ",".join(dto.strategies)
            binding.save()
        except DoesNotExist:
            # 新增记录
            binding = StrategyBinding.create(
                stock_category=dto.stock_category.value[0],
                stock_code=dto.stock_code,
                strategies=",".join(dto.strategies),
            )
        return StrategyBindingService._model_to_dto(binding)

    @staticmethod
    def delete_strategy_by_id(strategy_id: int) -> bool:
        """通过 ID 删除绑定策略"""
        query = StrategyBinding.delete().where(StrategyBinding.id == strategy_id)
        return query.execute() > 0

    @staticmethod
    def get_all_strategies() -> List[StrategyBindingDTO]:
        """查询所有绑定策略"""
        bindings = StrategyBinding.select()
        return [StrategyBindingService._model_to_dto(b) for b in bindings]

    @staticmethod
    def get_strategies_by_category(
        category: StockCategoryEnum,
    ) -> List[StrategyBindingDTO]:
        """通过分类查询绑定策略"""
        bindings = StrategyBinding.select().where(
            StrategyBinding.stock_category == category.value[0]
        )
        return [StrategyBindingService._model_to_dto(b) for b in bindings]

    @staticmethod
    def _model_to_dto(model: StrategyBinding) -> StrategyBindingDTO:
        """将数据库模型转换为 DTO"""
        return StrategyBindingDTO(
            id=model.id,
            stock_category=StockCategoryEnum(
                [e for e in StockCategoryEnum if e.value[0] == model.stock_category][0]
            ),
            stock_code=model.stock_code,
            strategies=model.strategies.split(","),
        )
